package common.mybatis;

import org.apache.ibatis.type.*;
import java.sql.*;
import com.alibaba.fastjson.*;

@MappedTypes(JSONArray.class) //指定该TypeHandler处理的Java类型为JSONArray
public class JSONArrayTypeHandler extends BaseTypeHandler<JSONArray> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONArray parameter, JdbcType jdbcType) throws SQLException {
        String jsonString = parameter.toJSONString();
        ps.setString(i, jsonString);
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJsonFromString(rs.getString(columnName));
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJsonFromString(rs.getString(columnIndex));
    }

    @Override
    public JSONArray getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJsonFromString(cs.getString(columnIndex));
    }

    private static JSONArray parseJsonFromString(String jsonString){
        if (jsonString == null || "".equals(jsonString)) {
            return new JSONArray();
        } else {
            try{
                return JSONObject.parseArray(jsonString);
            } catch (Exception e){
                throw new RuntimeException("Failed to convert string to JSONArray", e);
            }
        }
    }
}
